import calculation from "../../utils/calculation";

const state = {
    cartList: [],
    totalMoney: 0
}

const mutations = {
    TOGGLE_CART_LIST: (state, device) => {
        let total = device.total
        state.cartList.push(device)
        state.totalMoney = calculation.accAdd(state.totalMoney, total)
    },
    TOGGLE_EDIT_CART: (state, device) => {
        let data = state.cartList
        state.cartList = null
        let total = calculation.accSub(device.good.total, data[device.index].total)
        data[device.index] = device.good
        state.cartList = data
        state.totalMoney = calculation.accAdd(state.totalMoney, total)
        console.log(data)
    },
    TOGGLE_CLEAR_CART: (state) => {
        state.cartList = []
        state.totalMoney = 0
    },
    TOGGLE_DEL_CART: (state, device) => {
        let total = device.data.total
        state.cartList.splice(device.index,1)
        state.totalMoney = calculation.accSub(state.totalMoney, total)
    },
}

const actions = {
    addCart({commit}, device) {
        commit('TOGGLE_CART_LIST', device)
    },
    editCart({commit}, device) {
        commit('TOGGLE_EDIT_CART', device)
    },
    clearCart({commit}) {
        commit('TOGGLE_CLEAR_CART')
    },
    delCart({commit}, id) {
        commit('TOGGLE_DEL_CART', id)
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
